import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/index.vue'
import Layout from '../layout/index.vue'
import Articles from '../views/articles/index.vue'
//  路由守卫
import {
  getUser
} from '../utils/storage'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    // name: 'layout',
    component: Layout,
    children: [
      {
        path: '/articles',
        // name: 'articles',
        component: Articles
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
//  路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    const userInfo = getUser()
    //  判断有没有登录，能不能拿到token，否则返回登录界面
    if (userInfo && userInfo.token) {
      next()
    } else {
      next('/login')
    }
  } else {
    //  如果不是主页直接放行
    next()
  }
})
export default router
